const User = require('../models/user');
const jwt = require('jsonwebtoken');
const {secretKey} = require( '../config' )
const ObjectId = require('mongodb').ObjectId
const moment = require('moment');

const getUserAllTasks = async (req, res, next) => {

   
    try {
        await User.findOne({_id: new ObjectId(req.user.userId)})
                  .populate('taskList')
                  .then((user)=>{
                    
                    res.status(200).json({
                        tasklist:user.taskList,
                        message:"获取成功"
                    })
                  })
                  .catch((err)=> res.status(500).json(err))
       
    } catch (error) {
        console.error(error);
    }
};

const getTasksByStatus = async (req, res, next) => {
  const { status } = req.params;
  await User.findOne({_id: new ObjectId(req.user.userId)})
    .populate({ path: 'taskList', match: { status: status }})
    .then((user) => {
      const filteredTaskList = user.taskList.filter(task => task.status === status);
      res.status(200).json({
          tasklist: filteredTaskList,
          message: "获取成功"
      })
    })
    .catch((err) => res.status(500).json(err))
};



const addTask = async (req, res, next) => {

    const token = req.headers['authorization'].split(' ')[1]

    console.log(req.body)

    const {content,timestamp,status,level} = req.body

    let userPayload ={}

    jwt.verify(token,secretKey,(error,payload)=>{
        if(error) res.status(403)
        userPayload = payload
    })

    try {
        const user = await User.findOneAndUpdate(
        { _id: new ObjectId(userPayload.userId) },
        { $push: { taskList: { content, timestamp, status, level } } },
        { new: true }
        ).exec();
        
        let task = user.taskList[user.taskList.length - 1];
        
        res.status(200).json({
        success: true,
        message: "操作成功",
        data: task,
        });
        } catch (error) {
          res.status(500).json(error);
        }
};


const deleteTask = async (req, res, next) => {


    try {
        await User.findById({_id: new ObjectId(req.user.userId)})
                .then((user)=>{
                    let taskList = user.taskList
                    let taskIndex = taskList.findIndex((task)=> {
                        return task._id.toString() == req.body.taskId})
                    if (taskIndex !== -1) {
                        user.taskList.splice(taskIndex, 1);
                        user.save();
                        res.status(200).json({ success: true,message:'操作成功' });
                      } else {
                        res.json({ success: false });
                      }
                })
        
    }catch(error){
      res.status(500).json(error)
    }
}


const updateTask = async (req, res, next) => {
    console.log(req.body)
    try {
      const user = await User.findById(req.user.userId);
      if (!user) {
        return res.status(404).json({
          success: false,
          message: '用户不存在'
        });
      }
      let taskList = user.taskList;
      let taskIndex = taskList.findIndex(task => task._id.toString() === req.params.id);
      if (taskIndex === -1) {
        let = twiceFind = taskList.findIndex(task => task._id.toString() === req.body.id);
        if(twiceFind === -1)
          {
            return res.status(404).json({
              success: false,
              message: `任务 ${req.params.id} 不存在`
            });
          }
        taskIndex = twiceFind
      }
      const updateObj = {};
      if (req.body.content) {
        updateObj.content = req.body.content;
      }
      if (req.body.status) {
        updateObj.status = req.body.status;
      }
      if (req.body.timestamp){
        updateObj.timestamp = req.body.timestamp
      }
      if (req.body.level){
        updateObj.level = req.body.level
      }
      taskList[taskIndex] = Object.assign(taskList[taskIndex], updateObj);
      await user.save();
      res.status(200).json({
        success: true,
        message: '任务已更新',
        task: taskList[taskIndex]
      });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        success: false,
        message: '服务器错误'
      });
    }
  };
  

const countTaskByStatusInTheWeek = async(req,res,next) => {

  try {
    const userId = req.user.userId;
    const user = await User.findById(userId);
  
    const taskList = user.taskList;
    const today = moment().startOf('day');
    const weekStart = moment().subtract(6, 'days').startOf('day');
    const weekdays = 7;
    let finishedCount = 0;
    let doingCount = 0;
    let totalTasks = 0;
    let dailyData = [];
  
    for (let i = 0; i < weekdays; i++) {
      const dayStart = moment(weekStart).add(i, 'days');
      const weekday = dayStart.format('dddd');
      let finishedCountDay = 0;
      let doingCountDay = 0;
      taskList.forEach((task) => {
        const taskDay = moment(task.timestamp, 'YYYY-MM-DD');
        const daysAgo = dayStart.diff(taskDay, 'days');
        if (daysAgo === 0) {
          totalTasks++;
          if (task.status === 'finished') {
            finishedCount++;
            finishedCountDay++;
          } else if (task.status === 'doing') {
            doingCount++;
            doingCountDay++;
          }
        }
      });
  
      dailyData.push({
        day: i + 1,
        weekday,
        tasks: {
          finished: finishedCountDay,
          doing: doingCountDay,
          total: finishedCountDay + doingCountDay
        }
      });
    }
  
    const result = {
      dailyData,
      total: {
        finished: finishedCount,
        doing: doingCount,
        total: finishedCount + doingCount
      },
      totalTasks
    };
  
    res.status(200).json(result);
  } catch (err) {
    console.error(err);
    res.status(500).send('Internal Server Error');
  }
  
  
    
  

}


const tasks = [
    {
      content: 'Complete the project report',
      timestamp: '2022-12-25',
      status: 'In Progress',
      level: 'High'
    },
    {
      content: 'Attend the weekly team meeting',
      timestamp: '2022-12-26',
      status: 'Completed',
      level: 'Low'
    },
    {
      content: 'Submit the expense report',
      timestamp: '2022-12-27',
      status: 'In Progress',
      level: 'Medium'
    },
    {
      content: 'Follow up with the client',
      timestamp: '2022-12-28',
      status: 'Pending',
      level: 'High'
    },
    {
      content: 'Prepare for the presentation',
      timestamp: '2022-12-29',
      status: 'Not Started',
      level: 'Low'
    }
  ];
  


module.exports ={
    getUserAllTasks,
    addTask,
    deleteTask,
    updateTask,
    countTaskByStatusInTheWeek,
    getTasksByStatus
}